package com.jl.utils;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.jl.EmptyUtils;
import lombok.Builder;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * mybatisplus代码生成
 */
public class MybatisGenerator {

    @Data
    @Builder
    public static class Generator {
        //mysql连接url ip:端口/库名
        private String url;

        //mysql账号
        private String username;

        //mysql密码
        private String password;

        /**
         * 父路径 (例子 F:/idea-project/xy/xy-tools)
         */
        private String commPath;

        /**
         * 实体模块名 (例子 xy-mp)
         */
        private String entityModule;

        /**
         * 实体模块父包名 (例子 com.xy.test)
         */
        private String entityPackage;

        /**
         * dto模块名
         */
        private String dtoModule;

        /**
         * dto父包名
         */
        private String dtoPackage;

        /**
         * service模块名
         */
        private String serviceModule;

        /**
         * service父包名
         */
        private String servicePackage;

        /**
         * impl模块名
         */
        private String implModule;

        /**
         * impl父包名
         */
        private String implPackage;

        /**
         * mapper模块名
         */
        private String mapperModule;

        /**
         * mapper父包名
         */
        private String mapperPackage;

        /**
         * feign模块名
         */
        private String feignModule;

        /**
         * feign父包名
         */
        private String feignPackage;


        /* 下面非必填 */

        //实体父类
        private Class<?> baseEntity;

        //写于实体父类的表列 "id", "in_time", "modify_time"
        private String[] baseEntityPropertys;

        //作者
        private String author;

        //表名前缀
        private String tablePrefix;

        /**
         * 逻辑删除字段
         */
        private String deleteFieldName;

        /**
         * 主键类型
         */
        private IdType idType;

        public String getBaseEntity() {
            return baseEntity == null ? null : baseEntity.getName();
        }

        @SneakyThrows
        public void create() {
            generate(this);
        }
    }

    /**
     * 读取控制台内容
     */
    private static String[] scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        String str = scanner.next();
        String[] tables = str.split(",");
        return tables;
    }

    private static void generate(Generator generator) {
        String[] scanner = scanner("表名，多个,号分开");
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://" + generator.getUrl() + "?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(generator.getUsername());
        dsc.setPassword(generator.getPassword());
        // 包路径配置
        String commPath = generator.getCommPath();
        generates(generator, dsc, scanner, commPath + "/" + generator.getEntityModule(), generator.getEntityPackage(), 1);
        generates(generator, dsc, scanner, commPath + "/" + generator.getDtoModule(), generator.getDtoPackage(), 2);
        generates(generator, dsc, scanner, commPath + "/" + generator.getServiceModule(), generator.getServicePackage(), 3);
        generates(generator, dsc, scanner, commPath + "/" + generator.getImplModule(), generator.getImplPackage(), 4);
        generates(generator, dsc, scanner, commPath + "/" + generator.getMapperModule(), generator.getMapperPackage(), 5);
        if (EmptyUtils.check(generator.getFeignPackage())) {
            generates(generator, dsc, scanner, commPath + "/" + generator.getFeignModule(), generator.getFeignPackage(), 6);
        }
    }

    private static void generates(Generator generator, DataSourceConfig dsc, String[] scanner, String path, String packageStr, int type) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(path + "/src/main/java");
        gc.setAuthor(StringUtils.isEmpty(generator.getAuthor()) ? "xy" : generator.getAuthor());
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);
        gc.setEnableCache(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(false);
        gc.setSwagger2(true);
        //主键生成类型
        if (generator.getIdType() != null) {
            gc.setIdType(generator.getIdType());
        }

        // 包配置
        PackageConfig pc = new PackageConfig();
        //父包名
        pc.setParent(packageStr);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        //此处设置为null，就不会再文件
        templateConfig.setXml(null);
        templateConfig.setController(null);
        templateConfig.setEntity(null);
        templateConfig.setMapper(null);
        templateConfig.setService(null);
        templateConfig.setServiceImpl(null);
        mpg.setTemplate(templateConfig);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        //entity
        if (type == 1) {
            pc.setEntity("entity");
            templateConfig.setEntity(ConstVal.TEMPLATE_ENTITY_JAVA);
        }
        //dto
        if (type == 2) {
            pc.setXml("dto");
            List<FileOutConfig> focList = new ArrayList<>();
            focList.add(new FileOutConfig("/templates/dto.java.ftl") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                    return path + "/src/main/java/" + packageStr.replaceAll("\\.", "/") + "/dto/" + tableInfo.getEntityName() + "Dto" + StringPool.DOT_JAVA;
                }
            });
            cfg.setFileOutConfigList(focList);
        }
        //service
        if (type == 3) {
            gc.setServiceName("%sService");
            pc.setService("service");
            templateConfig.setService(ConstVal.TEMPLATE_SERVICE);
        }
        //serviceimpl
        if (type == 4) {
            pc.setXml("dto");
            pc.setServiceImpl("service");
            gc.setServiceName("%sService");
            gc.setServiceImplName("%sServiceImpl");
            templateConfig.setServiceImpl(ConstVal.TEMPLATE_SERVICE_IMPL);
        }
        //mapper
        if (type == 5) {
            gc.setMapperName("%sMapper");
            pc.setMapper("mapper");
            templateConfig.setMapper(ConstVal.TEMPLATE_MAPPER);
            // 生成xml
            List<FileOutConfig> focList = new ArrayList<>();
            // 自定义配置会被优先输出
            focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
                @Override
                public String outputFile(TableInfo tableInfo) {
                    // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                    return path + "/src/main/java/" + packageStr.replaceAll("\\.", "/") + "/mapper/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                }
            });
            cfg.setFileOutConfigList(focList);
        }
        //feign
        if (type == 6) {
            gc.setServiceName("%sService");
            gc.setControllerName("%sFeign");
            pc.setController("feign");
            templateConfig.setController(ConstVal.TEMPLATE_CONTROLLER);
        }
        mpg.setGlobalConfig(gc);
        // 数据源配置
        mpg.setDataSource(dsc);
        mpg.setPackageInfo(pc);
        mpg.setCfg(cfg);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        if (!StringUtils.isEmpty(generator.getBaseEntity())) {
            // 实体公共父类
            strategy.setSuperEntityClass(generator.getBaseEntity());
            // 写于父类的表列
            strategy.setSuperEntityColumns(generator.getBaseEntityPropertys());
        }
        strategy.setChainModel(true);
        strategy.setEntityLombokModel(true);
        // 表名
        strategy.setInclude(scanner);
        strategy.setControllerMappingHyphenStyle(true);
        //根据你的表名来建对应的类名，如果你的表名没有什么下划线，那么你就可以取消这一步
        if (!StringUtils.isEmpty(generator.getTablePrefix())) {
            strategy.setTablePrefix(generator.getTablePrefix());
        }
        //逻辑删除字段
        if (StrUtil.isNotEmpty(generator.getDeleteFieldName())) {
            strategy.setLogicDeleteFieldName(generator.getDeleteFieldName());
        }
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

